import { config, apiPaths } from '../config'
import { request } from './request'
import { mockTasks, mockAssignees, mockPriorities, mockStatuses } from '../mock/taskData'
import type { Task, Assignee, Priority, Status } from '../types/task'

// 接口返回类型定义
interface TaskListResponse {
  tasks: Task[]
  total: number
}

interface TaskResponse {
  task: Task
}

// 选项数据返回类型
interface OptionsResponse {
  assignees: Assignee[]
  priorities: Priority[]
  statuses: Status[]
}

// Mock数据处理函数
const mockDelay = <T>(data: T): Promise<T> => new Promise(resolve => setTimeout(() => resolve(data), 500))

// Task API
export const taskApi = {
  // 获取任务列表
  getTasks: async (): Promise<TaskListResponse> => {
    if (config.useMock) {
      return mockDelay<TaskListResponse>({
        tasks: mockTasks,
        total: mockTasks.length
      })
    }
    return request<TaskListResponse>({
      url: apiPaths.tasks.list
    })
  },

  // 获取任务详情
  getTaskDetail: async (taskId: string): Promise<TaskResponse> => {
    if (config.useMock) {
      const task = mockTasks.find(t => t.id === taskId)
      if (!task) throw new Error('Task not found')
      return mockDelay<TaskResponse>({ task })
    }
    return request<TaskResponse>({
      url: apiPaths.tasks.detail,
      params: { id: taskId }
    })
  },

  // 创建任务
  createTask: async (task: Omit<Task, 'id'>): Promise<TaskResponse> => {
    if (config.useMock) {
      const newTask = {
        ...task,
        id: `task-${Date.now()}`
      }
      mockTasks.push(newTask)
      return mockDelay<TaskResponse>({ task: newTask })
    }
    return request<TaskResponse>({
      url: apiPaths.tasks.create,
      method: 'POST',
      data: task
    })
  },

  // 更新任务
  updateTask: async (taskId: string, task: Partial<Task>): Promise<TaskResponse> => {
    if (config.useMock) {
      const index = mockTasks.findIndex(t => t.id === taskId)
      if (index === -1) throw new Error('Task not found')
      mockTasks[index] = { ...mockTasks[index], ...task }
      return mockDelay<TaskResponse>({ task: mockTasks[index] })
    }
    return request<TaskResponse>({
      url: apiPaths.tasks.update,
      method: 'PUT',
      params: { id: taskId },
      data: task
    })
  },

  // 删除任务
  deleteTask: async (taskId: string): Promise<void> => {
    if (config.useMock) {
      const index = mockTasks.findIndex(t => t.id === taskId)
      if (index === -1) throw new Error('Task not found')
      mockTasks.splice(index, 1)
      return mockDelay<void>(undefined)
    }
    return request<void>({
      url: apiPaths.tasks.delete,
      method: 'DELETE',
      params: { id: taskId }
    })
  },

  // 获取所有可选项
  getOptions: async (): Promise<OptionsResponse> => {
    if (config.useMock) {
      return mockDelay<OptionsResponse>({
        assignees: mockAssignees,
        priorities: mockPriorities,
        statuses: mockStatuses
      })
    }
    return request<OptionsResponse>({
      url: '/options'
    })
  }
} 